/*
 * Copyright (c) 2011 Jean-Marc Perronne
 * Ensisa, 12 rue des Freres Lumieres, F-68093 Mulhouse cedex
 * All rights reserved.
 *
 * The copyright of this software is owned by Werner Randelshofer. 
 * You may not use, copy or modify this software, except in  
 * accordance with the license agreement you entered into with  
 * Jean-Marc Perronne. For details see accompanying license terms. 
 */

package fr.uha.ensisa.jmp.drone.ui.cockpit;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.swing.JPanel;

public class VideoPanel extends JPanel
{
	protected BufferedImage image;
	protected BlockingQueue<VideoPanelDraft> drafts;

	public VideoPanel(Dimension dim)
	{
		this.drafts = new LinkedBlockingQueue<VideoPanelDraft>();
		this.setPreferredSize(dim);
	}

	public VideoPanel(BufferedImage image)
	{
		this.update(image);
	}
	
	public synchronized void addDraft(VideoPanelDraft draft)
	{
		this.drafts.add(draft);
	}
	
	protected synchronized void drawDrafts(Graphics2D g, BufferedImage videoImage)
	{
		while(true)
		{
			VideoPanelDraft draft = this.drafts.poll();
			if (draft == null) break;
			draft.draw(g ,videoImage);
		}
	}
	
	public void update(BufferedImage image)
	{
		this.image = image;
		this.setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));	
		this.repaint();
	}
	
	public void paintComponent(Graphics g)
	{
		super.paintComponent(g);
		if (this.image==null) return;
		
		java.awt.Rectangle b = this.getBounds(); 
		int dx = (b.width - this.image.getWidth()) / 2;
		int dy = (b.height - this.image.getHeight()) / 2;
		
		this.drawDrafts((Graphics2D) g, this.image);
		g.drawImage(this.image, dx, dy, null);
	}
}
